<?php
namespace app\common\model;
use think\Db;
/**
 * 会员模型
 */
class User extends Base {
	/**
	 * 判断用户登录帐号密码-店铺会员登录
	 */
	public function checkLogin(){
		$data = input("post.");
		if(!ZHTVerifyCheck($data['verifyCode'])){
			return ZHTReturn('验证码错误!',-1);
		}
		$rs = $this->where(['userAccount'=>$data['userAccount'],'userStatus'=>1,'dataFlag'=>1])->find();
		if(empty($rs))return ZHTReturn('账号错误!',-1);
		if($data['loginType'] == 1 and $rs['userType'] != 1)return ZHTReturn('您还没申请店铺!',-1);
		if($rs['userPass'] == md5($data['userPass'].$rs['secretKey'])){
	 		$rs->lastTime = time();
	 		$rs->lastIp = request()->ip();
	 		$rs->save();
      // 获取会员等级
      $rs_rank = ZHTUserRank($rs['userTotalScore']);      
			//如果是店铺则加载店铺信息
			if($rs['userType']==1){
				// 获取店铺信息
				$rs_shop = Db::name("shop")
					->where(["userId"=>$rs['userId'],"dataFlag" =>1,"shopStatus" =>1])->find();
				if($data['loginType'] == 1 and empty($rs_shop)){
					return ZHTReturn("店铺已停用，不能登录!",-1);
				}elseif($data['loginType'] == 0 and empty($rs_shop)){
					$rs['userType'] = 0;
					$rs_shop=[];
				}
				// 如果是店铺会员，则获取产业链信息
				if(!empty($rs_shop)){
					$rs_chain = Db::name("chain")->alias('c')
						->join('goods_cat gc','gc.catId=c.catId','left')
						->where(["c.shopId"=>$rs_shop['shopId'],"c.dataFlag" =>1])
						->field('c.catId,gc.catTitle')
						->select();
					$tmp = [];
					if(false != $rs_chain){					
						foreach($rs_chain as $v){
							$tmp[$v['catId']] = $v['catTitle'];
						}
					}
					$rs_shop['chain'] = $tmp;
				}
			}else{
				$rs_shop=[];
			}
			//记录登录日志
			$data_log = array();
			$data_log["userId"] = $rs['userId'];
			$data_log["loginTime"] = time();
			$data_log["loginIp"] = request()->ip();
			$data_log['loginSrc'] = 0;
			Db::name('log_user_login')->insert($data_log);

			//记住密码
			cookie("userAccount", $data['userAccount'], 3600*24*90);
			if($data['rememberPwd'] == 1){
				$datakey = md5($rs['userAccount'])."_".md5($rs['userPass']);
				$key = $rs['secretKey'];
				//加密
				require \Env::get('root_path') . 'extend/org/Base64.php';
				$base64 = new \org\Base64();
				$loginKey = $base64->encrypt($datakey, $key);
				cookie("userPass", $loginKey, 3600*24*90);
			}else{
				cookie("userPass", null);
			}
      $rs = array_merge($rs->toArray(),$rs_rank,$rs_shop);
	 		session("ZHT_USER",$rs);
			$friend['name']=iconv("utf-8","gbk//IGNORE",cookie("userPass"));
			$friend['name'] = mb_convert_encoding($friend['name'],'UTF-8','GBK');
			// return ZHTReturn('密码错误!',-1,$friend);
			return ZHTReturn("登录成功",1);
		}
		return ZHTReturn('密码错误!');
	}
	/**
	 * 根据cookie自动登录
	 */
	public function autoLoginByCookie(){
		$userAccount = cookie('userAccount');
		$loginKey = cookie("userPass");

		if($userAccount != '' && $loginKey != ''){
			$rs = $this->where(['userAccount'=>$userAccount,'userStatus'=>1,'dataFlag'=>1])->find();
			if(!empty($rs)){
				$datakey = md5($rs['userAccount'])."_".md5($rs['userPass']);
				$key = $rs['secretKey'];
				//加密
				require \Env::get('root_path') . 'extend/org/Base64.php';
				$base64 = new \org\Base64();
				$compareKey = $base64->encrypt($datakey, $key);
				//验证成功的话则补上登录信息
				if($compareKey == $loginKey){
					$rs->lastTime = time();
					$rs->lastIp = request()->ip();
					$rs->save();
					// 获取会员等级
					$rs_rank = ZHTUserRank($rs['userTotalScore']);      
					// 获取店铺信息
					//如果是店铺则加载店铺信息
					if($rs['userType']==1){
						$rs_shop = Db::name("shop")
							->where(["userId"=>$rs['userId'],"dataFlag" =>1,"shopStatus" =>1])->find();
						if(empty($rs_shop))$rs_shop=[];
						// 如果是店铺会员，则获取产业链信息
						if(!empty($rs_shop)){
							$rs_chain = Db::name("chain")->alias('c')
								->join('goods_cat gc','gc.catId=c.catId','left')
								->where(["c.shopId"=>$rs_shop['shopId'],"c.dataFlag" =>1])
								->field('c.catId,gc.catTitle')
								->select();
							$tmp = [];
							if(false != $rs_chain){					
								foreach($rs_chain as $v){
									$tmp[$v['catId']] = $v['catTitle'];
								}
							}
							$rs_shop['chain'] = $tmp;
						}
					}else{
						$rs_shop=[];
					}
					//记录登录日志
					$data_log = array();
					$data_log["userId"] = $rs['userId'];
					$data_log["loginTime"] = time();
					$data_log["loginIp"] = request()->ip();
					$data_log['loginSrc'] = 0;
					Db::name('log_user_login')->insert($data_log);

					$rs = array_merge($rs->toArray(),$rs_rank,$rs_shop);
					session("ZHT_USER",$rs);
				}
			}
		}
	}
	/**
	 * 获取指定id信息-home,shop共用
	 */
	public function getById($id){
		$rs = $this->get(['userId'=>$id]);
		// 获取会员等级
		$rs['rank'] = ZHTUserRank($rs['userTotalScore']);
		return $rs;
	}
	/**
	 * 修改-home,shop共用
	 */
	public function edit(){		
		$userId = (int)session('ZHT_USER.userId');
		$data = input('post.');
		
		Db::startTrans();// 启动事务
		try{
			//启用上传图片，需要在修改记录之前，比较上传的图片是否与数据表中的图片相同，从而决定是否修改图片启用还是无效
			ZHTUseResource(1, $userId, $data['userImg'], 'user', 'userImg');
			$rs = $this->save($data,['userId'=>(int)$userId]);
			if(false !== $rs){
				Db::commit();// 提交事务
				return ZHTReturn('操作成功',1);
			}else{
				return ZHTReturn($this->getError(),-1);
			}
		}catch (\Exception $e) {
			Db::rollback();// 回滚事务
		}
		return ZHTReturn('修改失败',-1);
	}
	/**
	 * 修改密码
	 */
	public function editPass(){
		$data = input('post.');
		$id = session('ZHT_USER.userId');
		$rs = $this->where('userId',$id)->field('secretKey,userPass')->find();
		if(empty($rs))return ZHTReturn('修改失败',-1);
		$userPassOld = md5($data["userPassOld"].$rs["secretKey"]);
		if($userPassOld != $rs['userPass'])return ZHTReturn('原密码错误',-1);
		$rs->userPass = md5($data["userPass"].$rs["secretKey"]);
		$result = $rs->save();
		if(false !== $result){
			return ZHTReturn("修改成功", 1);
		}else{
			return ZHTReturn($this->getError(),-1);
		}
	}
	/**
	 * 修改支付密码
	 */
	public function editPayPass(){
		$data = input('post.');
		$id = session('ZHT_USER.userId');
		$rs = $this->where('userId',$id)->field('secretKey,payPass')->find();
		if(empty($rs))return ZHTReturn('修改失败',-1);
		if(!empty($data["payPassOld"])){ // 如果旧密码存在，则修改支付密码
			$payPassOld = md5($data["payPassOld"].$rs["secretKey"]);
			if($payPassOld != $rs['payPass'])return ZHTReturn('原支付密码错误',-1);
			$rs->payPass = md5($data["payPass"].$rs["secretKey"]);
			$result = $rs->save();
			if(false !== $result){
				return ZHTReturn("修改成功", 1);
			}else{
				return ZHTReturn($this->getError(),-1);
			}
		}else{ // 如果旧密码不存在，则设置支付密码
			$rs->payPass = md5($data["payPass"].$rs["secretKey"]);
			$result = $rs->save();
			if(false !== $result){
				return ZHTReturn("修改成功", 1);
			}else{
				return ZHTReturn($this->getError(),-1);
			}
		}		
	}
	/**
	 * 忘记支付密码-发送邮件验证码
	 */
	public function forgetPayPassSendEmailCode(){		
		$data = input("post.");
		if (session('ZHT_USER.userEmail')==null) {
			return ZHTReturn('你没有预留邮箱，请联系客服找回密码！',-1);
		}
		if(!ZHTVerifyCheck($data['verifyCode'])){
			return ZHTReturn('验证码错误!',-1);
		}
		$code = rand(0,999999);
    $tpl = ZHTMsgTemplates('EMAIL_FORGET_PAYPASS');
		if($tpl['tplContent']!='' && $tpl['isShow']=='1'){
			$find = ['${LOGIN_NAME}','${SEND_TIME}','${VERFIY_CODE}','${VERFIY_TIME}'];
			$replace = [session('ZHT_USER.userAccount'),date('Y-m-d H:i:s'),$code,30];
			$sendRs = ZHTSendMail(session('ZHT_USER.userEmail'),'支付密码重置',str_replace($find,$replace,$tpl['tplContent']));
		}
		if($sendRs['status']==1){
			// 验证码
			session("paypass.code", $code);
			// 发起绑定邮箱的时间;
			session('paypass.time',time());
			return ZHTReturn('邮件发送成功',1);
		}else{
			return ZHTReturn('邮件发送失败',-1,$sendRs);
		}
	}
	/**
	 * 忘记支付密码-第一步-验证
	 */
	public function forgetPayPassCheck(){
		$data = input("post.");
		if(time()>floatval(session('paypass.time'))+30*60){
			return ZHTReturn("验证码已失效！");
		}
		if(session('paypass.code') != $data['emailCode'])return ZHTReturn('校验码错误',-1);
		return ZHTReturn("验证成功", 1);
	}
	/**
	 * 忘记支付密码-第二步-修改支付密码
	 */
	public function forgetPayPass2Check(){
		if(time()>floatval(session('paypass.time'))+30*60){
			return ZHTReturn("验证码已失效！");
		}
		$data = input('post.');
		$id = session('ZHT_USER.userId');
		$rs = $this->where('userId',$id)->field('secretKey,payPass')->find();
		if(empty($rs))return ZHTReturn('修改失败',-1);
		$rs->payPass = md5($data["payPass"].$rs["secretKey"]);
		$result = $rs->save();
		if(false !== $result){
			// 清空session
			session('paypass',null);
			return ZHTReturn("修改成功", 1);
		}else{
			return ZHTReturn($this->getError(),-1);
		}
	}
	/**
	 * 绑定邮箱-发送邮件验证码
	 */
	public function addEmailSendEmailCode(){
		$data = input("post.");
		if ($data['userEmail'] == '') {
			return ZHTReturn('请输入邮箱！',-1);
		}
		if(!ZHTVerifyCheck($data['verifyCode'])){
			return ZHTReturn('验证码错误!',-1);
		}
		$rs = ZHTCheckLoginKey($data['userEmail'],(int)session('ZHT_USER.userId'));
		if($rs["status"]!=1){
			return ZHTReturn("邮箱已存在!");
			exit();
		}
		$code = rand(0,999999);
    $tpl = ZHTMsgTemplates('EMAIL_BIND');
		if($tpl['tplContent']!='' && $tpl['isShow']=='1'){
			$find = ['${LOGIN_NAME}','${SEND_TIME}','${VERFIY_CODE}','${VERFIY_TIME}'];
			$replace = [session('ZHT_USER.userAccount'),date('Y-m-d H:i:s'),$code,30];
			$sendRs = ZHTSendMail($data['userEmail'],'绑定邮箱',str_replace($find,$replace,$tpl['tplContent']));
		}
		if($sendRs['status']==1){
			// 绑定的邮箱
			session('email.val',$data['userEmail']);
			// 验证码
			session("email.code", $code);
			// 发起绑定邮箱的时间;
			session('email.time',time());
			return ZHTReturn('邮件发送成功',1);
		}else{
			return ZHTReturn('邮件发送失败',-1,$sendRs);
		}
	}
	/**
	 * 绑定邮箱
	 */
	public function addEmail(){
		$data = input("post.");
		if(time()>floatval(session('email.time'))+30*60){
			return ZHTReturn("验证码已失效！");
		}
		$rs = ZHTCheckLoginKey(session('email.val'),(int)session('ZHT_USER.userId'));
		if($rs["status"]!=1){
			return ZHTReturn("邮箱已存在!");
			exit();
		}
		if(session('email.code') != $data['emailCode'])return ZHTReturn('校验码错误',-1);
		$rs = $this->update(['userEmail'=>session('email.val')],['userId'=>(int)session('ZHT_USER.userId')]);
		if(false !== $rs){
			session('ZHT_USER.userEmail',session('email.val'));
			// 清空session
			session('email',null);
			return ZHTReturn("绑定邮箱成功", 1);
		}else{
			return ZHTReturn($this->getError(),-1);
		}
	}
	/**
	 * 修改绑定邮箱-第一步-发送邮件验证码
	 */
	public function editEmailSendEmailCode(){
		$data = input("post.");
		if (session('ZHT_USER.userEmail')==null) {
			return ZHTReturn('你没有预留邮箱，请联系客服找回密码！',-1);
		}
		if(!ZHTVerifyCheck($data['verifyCode'])){
			return ZHTReturn('验证码错误!',-1);
		}
		$code = rand(0,999999);
    $tpl = ZHTMsgTemplates('EMAIL_EDIT');
		if($tpl['tplContent']!='' && $tpl['isShow']=='1'){
			$find = ['${LOGIN_NAME}','${SEND_TIME}','${VERFIY_CODE}','${VERFIY_TIME}'];
			$replace = [session('ZHT_USER.userAccount'),date('Y-m-d H:i:s'),$code,30];
			$sendRs = ZHTSendMail(session('ZHT_USER.userEmail'),'修改邮箱',str_replace($find,$replace,$tpl['tplContent']));
		}
		if($sendRs['status']==1){
			// 验证码
			session("email.code", $code);
			// 发起绑定邮箱的时间;
			session('email.time',time());
			return ZHTReturn('邮件发送成功',1);
		}else{
			return ZHTReturn('邮件发送失败',-1,$sendRs);
		}
	}
	/**
	 * 修改绑定邮箱-第一步-验证
	 */
	public function editEmail(){
		$data = input("post.");
		if(time()>floatval(session('email.time'))+30*60){
			return ZHTReturn("验证码已失效！");
		}
		if(session('email.code') != $data['emailCode'])return ZHTReturn('校验码错误',-1);
		return ZHTReturn("验证成功", 1);
	}
}